package cn.itrip.auth.controller;

import java.util.regex.Pattern;

import javax.annotation.Resource;

import cn.itrip.beans.pojo.ItripUser;
import cn.itrip.common.DtoUtil;
import cn.itrip.common.ErrorCode;
import cn.itrip.common.MD5;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import springfox.documentation.annotations.ApiIgnore;
import cn.itrip.auth.service.UserService;
import cn.itrip.beans.dto.Dto;
import cn.itrip.beans.vo.userinfo.ItripUserVO;

/**
 * 用户管理控制器
 *
 * @author hduser
 */
@Api("用户模块")
@Controller
@RequestMapping(value = "/api")
public class UserController {
    @Resource
    private UserService userService;

    @ApiIgnore
    @RequestMapping("/register")
    public String showRegisterForm() {
        return "register";
    }

    /**
     * 使用邮箱注册
     *
     * @param userVO
     * @return
     */
    @ApiOperation(value = "使用邮箱注册",httpMethod = "POST",protocols = "HTTP",produces = "application/json",response = Dto.class,notes = "使用邮箱注册")
    @ApiImplicitParam(name = "userVo",value = "用户实体",required = true)
    @ResponseBody
    @RequestMapping(value = "/doregister", method = RequestMethod.POST, produces = "application/json")
    public Dto doRegister(@RequestBody ItripUserVO userVO) {
        //1.邮箱验证
        if (!this.validEmail(userVO.getUserCode()))
            return DtoUtil.returnFail("请使用正确的邮箱地址", ErrorCode.AUTH_ILLEGAL_USERCODE);
        ItripUser user = new ItripUser();
        user.setUserCode(userVO.getUserCode());
        //user.setUserPassword(userVO.getUserPassword());
        user.setUserName(userVO.getUserName());
        try {
            if (null != userService.findUserByUserCode(user.getUserCode()))
                return DtoUtil.returnFail("用户已存在", ErrorCode.AUTH_USER_ALREADY_EXISTS);
            else {
                //2.调用业务层mailcreateuser
                user.setUserPassword(MD5.getMd5(userVO.getUserPassword(), 32));
                userService.mailCreateUser(user);
                return DtoUtil.returnSuccess();
            }
        } catch (Exception e) {
            e.printStackTrace();
            return DtoUtil.returnFail(e.getMessage(), ErrorCode.AUTH_UNKNOWN);
        }
    }

    /**
     * 邮箱激活
     * @param user
     * @param code
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/activate", method = RequestMethod.PUT, produces = "application/json")
    public Dto activate(@RequestParam String user, @RequestParam String code) {
        try {
            if (userService.mailActivate(user, code))
                return DtoUtil.returnSuccess("激活成功！");
            else
                return DtoUtil.returnSuccess("激活失败！");
        } catch (Exception e) {
            e.printStackTrace();
            return DtoUtil.returnFail("激活失败！", ErrorCode.AUTH_UNKNOWN);
        }
    }

    /**
     * 使用手机注册
     *
     * @param userVO
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/registerbyphone", method = RequestMethod.POST, produces = "application/json")
    public Dto registerByPhone(@RequestBody ItripUserVO userVO) {
        //手机号验证
        if(!this.validPhone(userVO.getUserCode()))
            return DtoUtil.returnFail("请使用正确的手机号码",ErrorCode.AUTH_ILLEGAL_USERCODE);
        //调用service
        ItripUser user= new ItripUser();
        user.setUserCode(userVO.getUserCode());
        user.setUserName(userVO.getUserName());
        try {
            if (null != userService.findUserByUserCode(user.getUserCode()))
                return DtoUtil.returnFail("用户已存在", ErrorCode.AUTH_USER_ALREADY_EXISTS);
            else {
                //2.调用业务层mailcreateuser
                user.setUserPassword(MD5.getMd5(userVO.getUserPassword(), 32));
                userService.phoneCreateUser(user);
                return DtoUtil.returnSuccess();
            }
        } catch (Exception e) {
            e.printStackTrace();
            return DtoUtil.returnFail(e.getMessage(), ErrorCode.AUTH_UNKNOWN);
        }
    }

    /**
     * 手机短信验证
     * @param user
     * @param code
     * @return
     */
    @ApiOperation(value = "使用手机注册用户短信认证",httpMethod = "PUT",protocols = "HTTP",produces = "手机注册短信认证")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "user",value = "手机号码"),
            @ApiImplicitParam(name = "code",value = "验证码")
    })
    @ResponseBody
    @RequestMapping(value = "/validatephone", method = RequestMethod.PUT, produces = "application/json")
    public Dto validatePhone(@RequestParam String user, @RequestParam String code) {
        try {
            if (userService.phoneValidate(user, code))
                return DtoUtil.returnSuccess("验证成功！");
            else
                return DtoUtil.returnSuccess("验证失败！");
        } catch (Exception e) {
            e.printStackTrace();
            return DtoUtil.returnFail("验证失败！", ErrorCode.AUTH_UNKNOWN);
        }
    }

	/**
	 * 检查用户是否已注册
	 *
	 * @return
	 * @param// name
	 */
	@ResponseBody
	@RequestMapping(value = "/ckusr", method = RequestMethod.GET, produces = "application/json")
	public Dto checkUser(@RequestParam String name) {
		return DtoUtil.returnSuccess();
	}

    /**
     * 合法E-mail地址：
     * 1. 必须包含一个并且只有一个符号“@”
     * 2. 第一个字符不得是“@”或者“.”
     * 3. 不允许出现“@.”或者.@
     * 4. 结尾不得是字符“@”或者“.”
     * 5. 允许“@”前的字符中出现“＋”
     * 6. 不允许“＋”在最前面，或者“＋@”
     */
    private boolean validEmail(String email) {
        String regex = "^\\s*\\w+(?:\\.{0,1}[\\w-]+)*@[a-zA-Z0-9]+(?:[-.][a-zA-Z0-9]+)*\\.[a-zA-Z]+\\s*$";
        return Pattern.compile(regex).matcher(email).find();
    }

    /**
     * 验证是否合法的手机号
     *
     * @param phone
     * @return
     */
    private boolean validPhone(String phone) {
        String regex = "^1[3578]{1}\\d{9}$";
        return Pattern.compile(regex).matcher(phone).find();
    }
}
